package com.hmall.search.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.feign.dto.PageDTO;
import com.hmall.search.constants.ESConstants;
import com.hmall.search.document.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import com.hmall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Slf4j
@Service
public class SearchServiceImpl implements SearchService {

    @Resource
    private RestHighLevelClient client;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 自动补全
     *
     * @param termPrefix 用户输入的词条前缀
     * @return 自动补全的词条集合
     * @throws IOException
     */
    @Override
    public List<String> suggestion(String termPrefix) throws IOException {
        SearchRequest request = new SearchRequest(ESConstants.ES_INDEX_NAME);
        // 构建 DSL 语句
        request.source().suggest(new SuggestBuilder()
                .addSuggestion(
                        "suggestions", // 自动补全名称
                        SuggestBuilders.completionSuggestion("suggestion") // 自动补全的字段
                                .prefix(termPrefix) // 输入的关键字
                                .skipDuplicates(true) // 跳过重复数据
                                .size(10) // 获取前10条数据
                )
        );
        // 发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 解析结果
        Suggest suggest = response.getSuggest();
        // 根据补全查询字段名称，获取补全结果
        CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
        // 获取options
        List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
        // 遍历数据
        List<String> list = new ArrayList<>(options.size());
        options.forEach(option -> {
            String text = option.getText().toString();
            list.add(text);
        });
        return list;
    }

    /**
     * 过滤项聚合
     *
     * @param params
     * @return
     * @throws IOException
     */
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) throws IOException {
        SearchRequest request = new SearchRequest(ESConstants.ES_INDEX_NAME);
        // 查询
        buildBasicQuery(params, request);
        request.source().size(0);
        // 聚合
        buildAggregation(request);
        // 发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 解析结果
        Aggregations aggregations = response.getAggregations();
        List<String> categoryList = getAggName(aggregations, "categoryAgg");
        List<String> brandList = getAggName(aggregations, "brandAgg");
        Map<String, List<String>> result = new HashMap<>();
        result.put("category", categoryList);
        result.put("brand", brandList);
        return result;
    }

    /**
     * 基本搜索
     *
     * @param params
     * @return
     * @throws IOException
     */
    @Override
    public PageDTO search(RequestParams params) throws IOException {
        SearchRequest request = new SearchRequest(ESConstants.ES_INDEX_NAME);

        // 多条件组合查询
        buildBasicQuery(params, request);

        // 分页处理
        int page = params.getPage();
        int size = params.getSize();
        request.source().from((page - 1) * size).size(size);

        // 排序处理，周边酒店
        String sortBy = params.getSortBy();
        if ("default".equals(sortBy)) {
            request.source().sort(SortBuilders
                    // 根据 sortBy 排序
                    .fieldSort("price")
                    // 升序，距离最近的酒店
                    .order(SortOrder.DESC)
            );
        } else if (null != sortBy && !"".equals(sortBy)) {
            request.source().sort(SortBuilders
                    // 根据 sortBy 排序
                    .fieldSort(sortBy)
                    // 升序，距离最近的酒店
                    .order(SortOrder.ASC)
            );
        }

        // 发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 解析响应
        return

                handleResponse(response);

    }

    private PageDTO handleResponse(SearchResponse response) {
        SearchHits searchHits = response.getHits();
        // 获取总条数
        Long total = searchHits.getTotalHits().value;
        log.info("total => {}", total);
        // 获取文档数组
        SearchHit[] hits = searchHits.getHits();
        List<ItemDoc> hotelDocs = new ArrayList<>();
        Arrays.stream(hits).forEach(hit -> {
            // 获取文档 source
            String json = hit.getSourceAsString();
            // 反序列化
            ItemDoc itemDoc = null;
            try {
                itemDoc = MAPPER.readValue(json, ItemDoc.class);
            } catch (JsonProcessingException e) {
                log.error("ItemDoc 反序列化失败, => {}", e.getMessage());
            }
            // 获取排序值
            // Object[] sortValues = hit.getSortValues();
            // if (sortValues.length > 0) {
            //     Object sortValue = sortValues[0];
            //     itemDoc.setDistance(sortValue);
            // }
            // 加入集合
            hotelDocs.add(itemDoc);
        });
        return new PageDTO(total, hotelDocs);
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 构建 BoolQueryBuilder 对象
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 关键字搜索
        String key = params.getKey();
        if (null == key || "".equals(key)) {
            // 查询所有
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            // 若查询的字段不为空，则根据该字段查询
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 分类条件
        if (null != params.getCategory() && !"".equals(params.getCategory())) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }

        // 品牌条件
        if (null != params.getBrand() && !"".equals(params.getBrand())) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }

        // 价格范围区间
        if (null != params.getMinPrice() && null != params.getMaxPrice()) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice() * 100).lte(params.getMaxPrice() * 100));
        }

        // 商品竞价算分
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                // 原始查询条件
                boolQuery,
                // function score的数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        // 其中一个function score元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                // 过滤条件
                                QueryBuilders.termQuery("isAD", true),
                                // 算分函数
                                ScoreFunctionBuilders.weightFactorFunction(100)
                        )
                }
                // 加权模式，设置为 sum
        ).scoreMode(FunctionScoreQuery.ScoreMode.SUM);

        request.source().query(functionScoreQuery);
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
    }

    private List<String> getAggName(Aggregations aggregations, String aggName) {
        // 根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        List<String> aggNameList = new ArrayList<>();
        buckets.forEach(bucket -> {
            String key = bucket.getKeyAsString();
            aggNameList.add(key);
        });
        return aggNameList;
    }
}
